package com.zhn.evsi.task.Evsi;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhn.evsi.common.RedisCache;
import com.zhn.evsi.domain.entity.evsi.EvsiAuthToken;
import com.zhn.evsi.domain.entity.evsi.EvsiCharacterWallet;
import com.zhn.evsi.domain.entity.System.SysMail;
import com.zhn.evsi.exception.CustomException;
import com.zhn.evsi.service.IEvsiAuthTokenService;
import com.zhn.evsi.service.IEvsiCharacterWalletJournalService;
import com.zhn.evsi.service.IEvsiCharacterWalletService;
import com.zhn.evsi.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class EvsiWalletTask {

    @Resource
    private MailUtil mailUtil;

    @Value("${eve.expected}")
    private Double expected;

    @Resource
    private RedisCache redisCache;

    @Autowired
    private IEvsiAuthTokenService authTokenService;

    @Autowired
    private IEvsiCharacterWalletService characterWalletService;

    @Autowired
    private IEvsiCharacterWalletJournalService characterWalletJournalService;

    // 每日夜晚11：00，获取用户当前的余额，并存入mysql中
    @Scheduled(cron = "* * 23 * * ? ")
//    @Scheduled(cron = "0 0/1 * * * ? ")
    @Transactional
    public void WalletTask() throws MessagingException {
        // 配置防止科学计数
        NumberFormat instance = NumberFormat.getInstance();
        instance.setGroupingUsed(false);

        log.info("钱包余额日报定时器执行 ================================");
        // TODO 获取当前用户id
        Integer characters = 2119634223;
        String characterName = "Vanity Liar";

        // 将当前用户的钱包余额存入mysql中
        Double wallet = characterWalletService.saveWallet();
        // 查询出来上次的钱包余额的，进行相减
        if (ObjectUtil.isNull(characters)){
            throw new CustomException("用户角色id缺失！");
        }
        int count = (int) characterWalletService.count(new LambdaQueryWrapper<EvsiCharacterWallet>()
                .eq(EvsiCharacterWallet::getCharacterId, characters));

        EvsiCharacterWallet evsiCharacterWallet = characterWalletService.list(new LambdaQueryWrapper<EvsiCharacterWallet>()
                .eq(EvsiCharacterWallet::getCharacterId, characters)).get(count - 2);
        if (ObjectUtil.isEmpty(evsiCharacterWallet)) {
            evsiCharacterWallet.setWallet(0.00);
        }

        // 昨日新增金额
        double addWallet = wallet - evsiCharacterWallet.getWallet();

        // 是否达到预期
        String ifSend = "";
        if (addWallet > expected) {
            ifSend = "今日预期成功完成！";
        }else {
            ifSend = "今日预期未完成！";
        }

        Calendar calendar = Calendar.getInstance();
        int date = calendar.get(Calendar.DATE);

        // TODO 预期差距
        Double walletRedis = redisCache.getCacheObject("wallet:" + characters);
        if (ObjectUtil.isNull(walletRedis) || date == 1) {
            walletRedis = 0.00;
        }
        double walletSet = walletRedis + expected - addWallet;
        redisCache.setCacheObject("wallet:" + characters, walletSet, 25, TimeUnit.HOURS);

        String standard = "";
        if (walletSet < 0) {
            standard = "高于";
        }else {
            standard = "低于";
        }

        // 并发送邮件通知
        SysMail sysMail = SysMail.builder()
                .receiveEmail("1085155177@qq.com")
                .subject(characterName + " 的钱包日余额报告")
                .content("当前 " + characterName + " 的钱包余额为: " + instance.format(wallet) + " (ISK); 且比昨日新增: " + instance.format(addWallet) + " (ISK); /n " +
                        "期望新增金额为：" + instance.format(expected) + " (ISK)," + ifSend + ", 预计每日" + standard +"目标：" + instance.format(Math.abs(walletSet)) + " (ISK)")
                .build();
//        sysMail = new SysMail();
//        sysMail.setReceiveEmail("1085155177@qq.com");
//        sysMail.setSubject(characterName + " 的钱包日余额报告");
//        sysMail.setContent("当前 " + characterName + " 的钱包余额为: " + instance.format(wallet) + " (ISK); 且比昨日新增: " + instance.format(addWallet) + " (ISK); /n " +
//                "期望新增金额为：" + instance.format(expected) + " (ISK)," + ifSend + ", 预计每日" + standard +"目标：" + instance.format(Math.abs(walletSet)) + " (ISK)");
        mailUtil.sendMail(sysMail);
    }

    // 扫描用户表，然后遍历用户表进行钱包记录遍历持久化
    @Scheduled(cron = "* 1 20 * * ? ")
    public void scheduledJournal() {
        log.info("定时器：获取所有角色钱包交易记录 <<<< ==== 20:01 / day ==== >>>>");
        List<EvsiAuthToken> evsiAuthTokens = authTokenService.oauthTokenList("");// 获取授权sql表中的数据
        evsiAuthTokens.forEach(v -> {
            characterWalletJournalService.journal(v);
        });
    }
}
